<template>
	<view class="chat">
		<scroll-view :style="{ height: `${windowHeight - inputHeight}rpx` }" id="scrollview" scroll-y="true" :scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-if="this.userid != 0">
					<view v-for="(item, index) in msgList" :key="index">
						<!-- 自己发的消息 -->
						<view class="item self" v-if="item.fromUser.id == login_user_id">
							<!-- 文字内容 -->
							<view class="content right">
								{{ item.message.content }}
							</view>
							<!-- 头像 -->
							<view class="avatar">
								<u--image :src="item.fromUser.usertx" width="40" height="40" shape="circle"></u--image>
							</view>
						</view>
						<!-- 判断时间 以上一次时间超过 10s 则显示时间 -->
						<view v-if="index != 0 && (index + 1) != msgList.length">
							<view class="time" v-if="(format_conversion(item.message.create_time) - format_conversion(msgList[index - 1].message.create_time)) > 120">
								{{ item.message.create_time }}
							</view>
						</view>
						<view class="item Ai" v-if="item.fromUser.id != login_user_id">
							<!-- 头像 -->
							<view class="avatar">
								<u--image :src="item.fromUser.usertx" width="40" height="40" shape="circle"></u--image>
							</view>
							<!-- 文字内容 -->
							<view class="content left">
								{{ item.message.content }}
							</view>
						</view>
					</view>
				</view>
				<view v-else>
					<view v-for="(item, index) in msgList" :key="index">
						<view class="time">
							{{ item.time }}
						</view>
						<view class="item Ai">
							<!-- 头像 -->
							<view class="avatar">
								<u--image src="/static/images/message-notification.png" width="40" height="40" shape="circle"></u--image>
							</view>
							<!-- 文字内容 -->
							<view class="content left">
								{{ item.content }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{ height: `${inputHeight}rpx` }" v-if="this.userid != 0">
			<view class="send-msg" :style="{ bottom: `${keyboardHeight}rpx` }">
				<view class="uni-textarea">
					<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend" :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus" @blur="blur" auto-height></textarea>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
export default {
	data() {
		return {
			//键盘高度
			keyboardHeight: 0,
			//底部消息发送高度
			bottomHeight: 0,
			//滚动距离
			scrollTop: 0,
			userid: '',
			login_user_id: '',
			//发送的消息
			chatMsg: "",
			msgList: [],
			get_chat_log_timer: null,
			user_information: {}
		}
	},
	updated() {
		//页面更新时调用聊天消息定位到最底部
		this.scrollToBottom();
	},
	computed: {
		windowHeight() {
			return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
		},
		// 键盘弹起来的高度+发送框高度
		inputHeight() {
			return this.bottomHeight + this.keyboardHeight + 20
		}
	},
	onLoad(options) {
		//获取登录用户id
		this.login_user_id = uni.getStorageSync('userid');
		if (this.login_user_id == '') {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			uni.navigateTo({
				url: '/pages/login/login'
			});
			return false;
		}
		this.userid = options.userid;
		// 定时器获取聊天记录
		if (this.userid == 0) {
			this.get_message_notifications();
			uni.setNavigationBarTitle({
				title: "系统消息"
			});
		} else {
			this.get_user_information(this.userid);
			this.get_chat_log(this.userid);
			this.get_chat_log_timer = setInterval(() => {
				this.get_chat_log(this.userid);
			}, 5000);
		}
		uni.onKeyboardHeightChange(res => {
			//这里正常来讲代码直接写
			//this.keyboardHeight=this.rpxTopx(res.height)就行了
			//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
			this.keyboardHeight = this.rpxTopx(res.height - 30)
			if (this.keyboardHeight < 0) this.keyboardHeight = 0;
		})
	},
	onUnload() {
		if (this.get_chat_log_timer) {
			clearInterval(this.get_chat_log_timer);
			this.get_chat_log_timer = null;
		}
	},
	methods: {
		// 获取聊天记录
		async get_chat_log(userid) {
			let get_chat_log = await this.$api.get_chat_log({
				receiver_id: userid,
				limit: 1000,
			});
			if (get_chat_log.code == 1) {
				this.msgList = get_chat_log.data.list.reverse();
				this.scrollToBottom()
			}
		},
		focus() {
			this.scrollToBottom()
		},
		blur() {
			this.scrollToBottom()
		},
		// px转换成rpx
		rpxTopx(px) {
			let deviceWidth = wx.getSystemInfoSync().windowWidth
			let rpx = (750 / deviceWidth) * Number(px)
			return Math.floor(rpx)
		},
		// 监视聊天发送栏高度
		sendHeight() {
			setTimeout(() => {
				let query = uni.createSelectorQuery();
				query.select('.send-msg').boundingClientRect()
				query.exec(res => {
					this.bottomHeight = this.rpxTopx(res[0].height)
				})
			}, 10)
		},
		// 滚动至聊天底部
		scrollToBottom(e) {
			setTimeout(() => {
				let query = uni.createSelectorQuery().in(this);
				query.select('#scrollview').boundingClientRect();
				query.select('#msglistview').boundingClientRect();
				query.exec((res) => {
					if (res[1].height > res[0].height) {
						this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
					}
				})
			}, 15)
		},
		// 发送消息
		handleSend() {
			//如果消息不为空
			if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
				let obj = {
					botContent: "",
					recordId: 0,
					titleId: 0,
					userContent: this.chatMsg,
					userId: 0
				}
				this.send_message();
			} else {
				uni.showToast({
					title: '请输入内容',
					icon: 'none'
				})
			}
		},
		// 发送消息 提交到后台
		async send_message() {
			if (this.chatMsg == '') {
				uni.showToast({
					title: '请输入内容',
					icon: 'none'
				});
				return false;
			}
			let send_msg = await this.$api.send_message({
				receiver_id: this.userid,
				content: this.chatMsg
			});
			if (send_msg.code == 1) {
				this.chatMsg = '';
				this.scrollToBottom();
				this.get_chat_log(this.userid);
			}
		},
		//时间格式转换 传入2019-12-12 12:12:12格式的时间 返回13为时间戳
		format_conversion(date) {
			let timestamp = Date.parse(new Date(date).toString());
			timestamp = timestamp / 1000;
			return timestamp;
		},
		//获取系统消息
		async get_message_notifications() {
			let get_message_notifications = await this.$api.get_message_notifications({
				limit: 1000,
				page: 1
			});
			if (get_message_notifications.code == 1) {
				this.msgList = get_message_notifications.data.list.reverse();
			}
		},
		// 获取用户信息
		get_user_information(id) {
			this.$api.get_user_information({ userid: id }).then((res) => {
				if (res.code == 1) {
					this.user_information = res.data;
					uni.setNavigationBarTitle({
						title: res.data.nickname
					});
				}
			}).catch((err) => {
				this.loading = false;
				console.log('request fail', err);
			})
		},
	}
}
</script>
<style lang="less">
view,
button,
text,
input,
textarea {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

/* 聊天消息 */
.chat {
	.scroll-view {
		::-webkit-scrollbar {
			display: none;
			width: 0 !important;
			height: 0 !important;
			-webkit-appearance: none;
			background: transparent;
			color: transparent;
		}

		// background-color: orange;
		background-color: #F6F6F6;

		.chat-body {
			display: flex;
			flex-direction: column;
			padding-top: 23rpx;
			// background-color:skyblue;

			.self {
				justify-content: flex-end;
			}

			.item {
				display: flex;
				padding: 23rpx 30rpx;
				// background-color: greenyellow;

				.right {
					background-color: #C2DCFF;
				}

				.left {
					background-color: #FFFFFF;
				}

				// 聊天消息的三角形
				.right::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					left: 100%;
					top: 10px;
					border: 12rpx solid transparent;
					border-left: 12rpx solid #C2DCFF;
				}

				.left::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					top: 10px;
					right: 100%;
					border: 12rpx solid transparent;
					border-right: 12rpx solid #FFFFFF;
				}

				.content {
					position: relative;
					max-width: 486rpx;
					border-radius: 8rpx;
					word-wrap: break-word;
					padding: 24rpx 24rpx;
					margin: 0 24rpx;
					border-radius: 5px;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
					line-height: 42rpx;
				}

				.avatar {
					display: flex;
					justify-content: center;
					width: 78rpx;
					height: 78rpx;
					border-radius: 8rpx;
					overflow: hidden;

					image {
						align-self: center;
					}

				}
			}

			.time {

				display: flex;
				justify-content: center;
				align-items: center;
				margin: 20rpx 0;
				font-size: 24rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #999999;
				line-height: 24rpx;
			}
		}
	}

	/* 底部聊天发送栏 */
	.chat-bottom {
		width: 100%;
		height: 177rpx;
		background: #F4F5F7;
		transition: all 0.1s ease;

		.send-msg {
			display: flex;
			align-items: center;
			padding: 16rpx 30rpx;
			width: 100%;
			position: fixed;
			bottom: 0;
			background: #EDEDED;
			transition: all 0.1s ease;
		}

		.uni-textarea {

			textarea {
				width: 537rpx;
				min-height: 75rpx;
				max-height: 500rpx;
				background: #FFFFFF;
				border-radius: 8rpx;
				font-size: 32rpx;
				font-family: PingFang SC;
				color: #333333;
				line-height: 43rpx;
				padding: 5rpx 8rpx;
			}
		}



		.send-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: 25rpx;
			width: 128rpx;
			height: 75rpx;
			background: #4F7DF5;
			border-radius: 8rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 28rpx;
		}
	}
}
</style>
